<template>
  <van-button
    v-if="isFollowed"
    class="follow-btn"
    round
    :loading="loading"
    size="small"
    @click="Follow"
    >已关注</van-button
  >
  <van-button
    v-else
    class="follow-btn"
    type="info"
    color="#3296fa"
    round
    :loading="loading"
    size="small"
    icon="plus"
    @click="Follow"
    >关注</van-button
  >
</template>

<script>
import { addFollow, deleteFollow } from '@/api/user'
export default {
  name: 'followuser',
  // 自定义v-model的数据名称
  model: {
    prop: 'isFollowed', // 默认是value
    event: 'update-is-followed' // 默认是input
  },
  props: {
    isFollowed: {
      type: Boolean,
      required: true
    },
    userId: {
      type: [Number, String, Object],
      required: true
    }
  },
  data () {
    return {
      loading: false
    }
  },

  methods: {
    async Follow () {
      // 展示点击关注用户的加载效果
      this.loading = true
      try {
        if (this.isFollowed.is_followed) {
          // 已关注，点击则取消关注
          await deleteFollow(this.userId)
        } else {
          // 没关注，点击则关注
          await addFollow(this.userId)
        }
        // 更新视图状态
        // this.article.is_followed = !this.article.is_followed;
        this.$emit('update-is-followed', !this.isFollowed)
        // this.$emit("input", !this.isFollowed);
      } catch (error) {
        let message = '操作失败，稍后重试'
        if (error.response && error.response.status === 400) {
          message = '不能关注自己！'
        }
        this.$toast(message)
      }
      this.loading = false // 关闭loading效果
    }
  }
}
</script>

<style>
</style>
